import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useWhiteNoiseStore = defineStore('whiteNoise', () => {
  // 白噪音数据
  const whiteNoises = ref([
    { name: 'rain', label: '雨声', file: '9-relaxing-rain-water-green-noise.mp3', volume: 50, enabled: false, audio: null },
    { name: 'cafe', label: '咖啡馆', file: 'cafe-noise.mp3', volume: 50, enabled: false, audio: null },
    { name: 'city', label: '城市', file: 'city-noise.mp3', volume: 50, enabled: false, audio: null },
    { name: 'fire', label: '火焰', file: 'fire-sound.mp3', volume: 50, enabled: false, audio: null },
    { name: 'rain_light', label: '雨声', file: 'rainy-day-in-town-with-birds-singing.mp3', volume: 50, enabled: false, audio: null },
    { name: 'sea', label: '海浪', file: 'sea-waves.mp3', volume: 50, enabled: false, audio: null },
    { name: 'road', label: '街道', file: 'road-transport-noise.mp3', volume: 50, enabled: false, audio: null }
  ])

  // 主控制状态
  const masterEnabled = ref(false)
  const masterVolume = ref(70)
  const currentPreset = ref(null)
  const currentBackgroundColor = ref('#2563eb')
  
  // 粒子动画状态
  const currentParticleType = ref(null)
  
  // 是否已初始化音频
  const audioInitialized = ref(false)

  // 初始化音频
  const initializeAudio = async () => {
    if (audioInitialized.value) return
    
    for (const noise of whiteNoises.value) {
      if (!noise.audio) {
        const audioPath = window.electronAPI ? 
          await window.electronAPI.getResourcePath(`noise/${noise.file}`) : 
          `/noise/${noise.file}`
        noise.audio = new Audio(audioPath)
        noise.audio.loop = true
        noise.audio.volume = (noise.volume / 100) * (masterVolume.value / 100)
      }
    }
    audioInitialized.value = true
  }

  // 切换噪音
  const toggleNoise = async (noiseName) => {
    const noise = whiteNoises.value.find(n => n.name === noiseName)
    if (noise) {
      noise.enabled = !noise.enabled
      
      if (noise.enabled) {
        // 当打开某个声音时，自动开启总开关
        if (!masterEnabled.value) {
          masterEnabled.value = true
        }
        
        if (!noise.audio) {
          const audioPath = window.electronAPI ? 
            await window.electronAPI.getResourcePath(`noise/${noise.file}`) : 
            `/noise/${noise.file}`
          noise.audio = new Audio(audioPath)
          noise.audio.loop = true
        }
        
        // 开始播放并应用淡入效果
        const targetVolume = (noise.volume / 100) * (masterVolume.value / 100)
        await noise.audio.play().catch(e => console.log('Audio play failed:', e))
        await fadeInAudio(noise.audio, targetVolume)
      } else {
        if (noise.audio) {
          noise.audio.pause()
          noise.audio.currentTime = 0
        }
        
        // 检查是否所有声音都关闭了，如果是则关闭总开关
        const hasEnabledNoise = whiteNoises.value.some(n => n.enabled)
        if (!hasEnabledNoise) {
          masterEnabled.value = false
        }
      }
    }
  }

  // 停止所有噪音
  const stopAllNoise = () => {
    whiteNoises.value.forEach(noise => {
      noise.enabled = false
      if (noise.audio) {
        noise.audio.pause()
        noise.audio.currentTime = 0
      }
    })
    currentPreset.value = null
    masterEnabled.value = false
  }

  // 设置噪音音量
  const setNoiseVolume = (noiseName, volume) => {
    const noise = whiteNoises.value.find(n => n.name === noiseName)
    if (noise) {
      const volumeValue = parseInt(volume)
      noise.volume = volumeValue
      if (noise.audio) {
        noise.audio.volume = (volumeValue / 100) * (masterVolume.value / 100)
      }
    }
  }

  // 切换主开关
  const toggleMaster = async () => {
    masterEnabled.value = !masterEnabled.value
    
    if (!masterEnabled.value) {
      // 暂停所有音频但保持enabled状态
      whiteNoises.value.forEach(noise => {
        if (noise.audio && noise.enabled) {
          noise.audio.pause()
        }
      })
    } else {
      // 恢复播放所有enabled的音频并应用淡入效果
      const fadePromises = []
      whiteNoises.value.forEach(noise => {
        if (noise.audio && noise.enabled) {
          const targetVolume = (noise.volume / 100) * (masterVolume.value / 100)
          noise.audio.play().catch(e => console.log('Audio play failed:', e))
          fadePromises.push(fadeInAudio(noise.audio, targetVolume))
        }
      })
      // 等待所有音频淡入完成
      await Promise.all(fadePromises)
    }
  }

  // 更新主音量
  const updateMasterVolume = (volume) => {
    const volumeValue = parseInt(volume)
    masterVolume.value = volumeValue
    whiteNoises.value.forEach(noise => {
      if (noise.audio && noise.enabled) {
        noise.audio.volume = (noise.volume / 100) * (masterVolume.value / 100)
      }
    })
  }

  // 应用预设
  const applyPreset = async (preset) => {
    // 停止所有当前播放的声音
    whiteNoises.value.forEach(noise => {
      noise.enabled = false
      if (noise.audio) {
        noise.audio.pause()
        noise.audio.currentTime = 0
      }
    })
    
    // 等待一小段时间确保音频停止
    await new Promise(resolve => setTimeout(resolve, 100))
    
    // 应用预设
    currentPreset.value = preset.id
    currentBackgroundColor.value = preset.backgroundColor
    currentParticleType.value = preset.particleType
    
    // 自动开启总开关
    masterEnabled.value = true
    
    // 应用预设音频并使用淡入效果
    const fadePromises = []
    for (const presetNoise of preset.noises) {
      const noise = whiteNoises.value.find(n => n.name === presetNoise.name)
      if (noise) {
        noise.volume = presetNoise.volume
        noise.enabled = true
        
        if (!noise.audio) {
          const audioPath = window.electronAPI ? 
            await window.electronAPI.getResourcePath(`noise/${noise.file}`) : 
            `/noise/${noise.file}`
          noise.audio = new Audio(audioPath)
          noise.audio.loop = true
        }
        
        const targetVolume = (noise.volume / 100) * (masterVolume.value / 100)
        await noise.audio.play().catch(e => console.log('Audio play failed:', e))
        fadePromises.push(fadeInAudio(noise.audio, targetVolume))
      }
    }
    
    // 等待所有音频淡入完成
    await Promise.all(fadePromises)
  }

  // 获取当前活跃的粒子类型
  const getActiveParticleType = () => {
    if (currentPreset.value) {
      return currentParticleType.value
    }
    
    const enabledNoises = whiteNoises.value.filter(n => n.enabled)
    if (enabledNoises.length > 0) {
      let particleType = enabledNoises[0].name
      if (particleType === 'rain_light') {
        particleType = 'rain'
      }
      return particleType
    }
    
    return null
  }

  // 检查是否有音频在播放
  const hasActiveAudio = () => {
    return masterEnabled.value && whiteNoises.value.some(n => n.enabled)
  }

  // 清除当前预设
  const clearCurrentPreset = () => {
    currentPreset.value = null
    currentParticleType.value = null
  }

  // 音量淡入效果
  const fadeInAudio = (audio, targetVolume, duration = 2000) => {
    if (!audio) return Promise.resolve()
    
    return new Promise((resolve) => {
      const startVolume = 0
      const volumeStep = targetVolume / (duration / 50) // 每50ms的音量增量
      let currentVolume = startVolume
      
      audio.volume = startVolume
      
      const fadeInterval = setInterval(() => {
        currentVolume += volumeStep
        
        if (currentVolume >= targetVolume) {
          audio.volume = targetVolume
          clearInterval(fadeInterval)
          resolve()
        } else {
          audio.volume = currentVolume
        }
      }, 50)
    })
  }

  return {
    // 状态
    whiteNoises,
    masterEnabled,
    masterVolume,
    currentPreset,
    currentBackgroundColor,
    currentParticleType,
    audioInitialized,
    
    // 方法
    initializeAudio,
    toggleNoise,
    stopAllNoise,
    setNoiseVolume,
    toggleMaster,
    updateMasterVolume,
    applyPreset,
    getActiveParticleType,
    hasActiveAudio,
    clearCurrentPreset,
    fadeInAudio
  }
})